/**
 * 表单的初始值及校验
 * @author SPY
 * @date 2020/01/16
 */

import moment from 'moment';


/**
 * 将字串符或者时间戳转化为moment对象
 * @param {*} date 
 * @param {*} format 
 */
function isDateStr(date, format) {
    let d = date;
    const f = format || 'YYYY-MM-DD';
    if (typeof d === 'number' || (d.indexOf('-') < 0 && d.indexOf('/') < 0)) {
        d = moment(Number(d)).format(f);
    }
    return moment(d, f);
}

/**
 * 把日期类型的初始值改为moment对象，支持字符串和时间戳,字符串‘-’或者‘/’分割
 * @param {object} item
 */
function transform(item) {
    switch (item.type) {
        case 'DatePicker':
            return item.initialValue && isDateStr(item.initialValue, item.format);
        case 'RangePicker':
            return (
                Array.isArray(item.initialValue) && [
                    isDateStr(item.initialValue[0], item.format),
                    isDateStr(item.initialValue[1], item.format),
                ]
            );
        default:
            return item.initialValue;
    }
}


const Config = (item) => {
    const formConfig = {
        initialValue: transform(item),
        rules: [
            {
                required: typeof item.required === 'boolean' ? item.required : false,  // 默认不必填
                message: item.type === 'Input' ? `请输入${item.label}` : `请选择${item.label}`,
            }
        ]
    };
    return formConfig;
}

export default Config;